package com.yangtao.springbootfreemarker.domain.sys.service.impl;

import com.yangtao.core.jpa.service.impl.BaseJpaServiceImpl;
import com.yangtao.core.shiro.service.impl.ShiroSecurityService;
import com.yangtao.core.utils.CollectionUtil;
import com.yangtao.core.utils.StringUtil;
import com.yangtao.core.utils.TreeUtil;
import com.yangtao.springbootfreemarker.domain.sys.dao.SysMenuDao;
import com.yangtao.springbootfreemarker.domain.sys.entity.SysMenu;
import com.yangtao.springbootfreemarker.domain.sys.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl extends BaseJpaServiceImpl<SysMenu, String, SysMenuDao> implements SysMenuService {

	@Autowired
	private ShiroSecurityService shiroSecurityService;
	@Autowired
	private SysMenuDao sysMenuDao;
	@Override
	public List<SysMenu> getUserMenuList() {
		List<SysMenu> menuList = new ArrayList<>();
		if(shiroSecurityService.isAdmin()) {
			menuList = findAll(Sort.by("orderNum"));
		} else {
			menuList = sysMenuDao.findAllMenuByUserId(shiroSecurityService.getUserId(), shiroSecurityService.getOrgId());
		}
		menuList = menuList.stream().filter(new Predicate<SysMenu>() {
			@Override
			public boolean test(SysMenu sysMenu) {
				return !StringUtil.equals(sysMenu.getType(), SysMenu.Type.BTN.getValue());
			}
		}).collect(Collectors.toList());
		try {
			return TreeUtil.getTree(menuList, "menuId", "0", "parentId", "children");
		} catch (Exception e) {
			return CollectionUtil.newArrayList();
		}
	}
}
